package cc.vv.party.service.impl;

import cc.vv.party.beans.model.Image
import cc.vv.party.beans.model.TeamSignIn;
import cc.vv.party.beans.vo.SignInVO
import cc.vv.party.beans.vo.TeamWorkVO
import cc.vv.party.mapper.TeamSignInMapper;
import cc.vv.party.service.TeamSignInService;
import cc.vv.party.common.base.BaseServiceImpl;
import cc.vv.party.common.constants.StatusCode
import cc.vv.party.common.ext.uuid
import cc.vv.party.exception.BizException
import cc.vv.party.mapper.ImageMapper
import cc.vv.party.mapper.TeamMapper
import cc.vv.party.param.TeamSignInParam
import cn.hutool.core.date.DatePattern
import cn.hutool.core.date.DateUtil
import com.baomidou.mybatisplus.mapper.EntityWrapper
import commonx.core.content.transfer
import org.apache.commons.collections.CollectionUtils
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional
import java.util.*

/**
 * <p>
 * 四支队伍信息 服务实现类
 * </p>
 *
 * @author Gyb
 * @since 2018-10-12
 */
@Service
open class TeamSignInServiceImpl : BaseServiceImpl<TeamSignInMapper, TeamSignIn>(), TeamSignInService {

    @Autowired
    lateinit var teamMapper: TeamMapper

    @Autowired
    lateinit var imageMapper: ImageMapper

    @Transactional(rollbackFor = [(Exception::class)])
    override fun signIn(param: TeamSignInParam, userId: String): Boolean {
        val count = super.selectCount(EntityWrapper<TeamSignIn>().where("team_id = {0}", param.teamId)
                .and("sign_type = {0}", param.signType)
                .and("DATE_FORMAT(sign_time, '%Y-%m-%d') = {0}", DateUtil.format(Date(), DatePattern.NORM_DATE_PATTERN)))
        if(count > 0){
            throw BizException(StatusCode.MESSAGE_EXIST.statusCode, "您已经签过到，请勿重复签到！")
        }

        var teamSignIn = param.transfer<TeamSignIn>()
        teamSignIn.id = uuid()
        teamSignIn.signTime = Date(System.currentTimeMillis())
        teamSignIn.createUser = userId
        super.insert(teamSignIn)

        if(CollectionUtils.isNotEmpty(param.imgList)){
            for(str in param.imgList!!){
                var img = Image()
                img.type = Integer(0)
                img.associaId = teamSignIn.id
                img.url = str
                imageMapper.insert(img)
            }
        }
        return true
    }

    override fun info(teamId: String, time: String): SignInVO {
        var result = SignInVO()

        result.time = time

        var teamSignInList = baseMapper.findTeamSignInByTeamIdAndCreateTime(teamId, time)

        var team = teamMapper.selectById(teamId) ?: throw BizException(StatusCode.MESSAGE_NOT_EXIST.statusCode, "队伍信息不存在")

        result.teamSignInList = teamSignInList
        result.teamVO = team.transfer()

        return result
    }

}
